<script type="text/javascript" charset="utf-8">
var template = '<?php echo $template; ?>';
var paginator = {
    init: function (elemCounter, elemNumbers, gotoMethod, total, limit, counterTpl) {
        this.pageData = {
            limit: 25,
            counterTpl: 'Showing #{start} - #{end} of #{total} records',
            prev: '&lt; previous',
            next: 'next &gt;',
            range: 8
        }
        this.elemCounter = 'pageCounter';
        this.elemNumbers = 'pageNumbers';
        this.gotoMethod  = 'paginator.gotoPage';

        if (elemCounter === false) {
            this.elemCounter = false;
        }
        if (elemNumbers === false) {
            this.elemNumbers = false;
        }
        if (gotoMethod) {
            this.gotoMethod = gotoMethod;
        }
        if (typeof(limit) != 'undefined' && limit) {
            this.pageData.limit = limit;
        }
        if (typeof(counterTpl) != 'undefined' && counterTpl) {
            this.pageData.counterTpl = counterTpl;
        }

        this.pageData.page    = 1;
        this.pageData.pages   = Math.ceil(total / this.pageData.limit);
        this.pageData.current = (total >= this.pageData.limit) ? this.pageData.limit : total;
        this.pageData.total   = total;
        this.pageData.start   = 1;
        this.pageData.end     = this.pageData.current;
        this.pageData.counter = new Template(this.pageData.counterTpl).evaluate(this.pageData);

        if (this.elemCounter) {
            var c = this.pageData.counter;
            $$('.'+this.elemCounter).each(function(e){
                e.update(c);
            });
        }

        if (this.pageData.pages < 2) { // only 1 page
            var n = this.pageData.paging = '<span class="current">1</span>';
            $$('.'+this.elemNumbers).each(function(e){
                e.update(n);
            });
            return;
        }

        this.pageData.paging = '<div class="disabled">'+this.pageData.prev+'</div><span class="current">1</span>';
        for (var i=2; i<=this.pageData.range; i++) {
            if (i > this.pageData.pages) { break; }
            this.pageData.paging += '<span class="link" onclick="'+this.gotoMethod+'('+i+')">'+i+'</span>';
        }
        this.pageData.paging += '<div class="link" onclick="'+this.gotoMethod+'(2)">'+this.pageData.next+'</div>';

        if (this.elemNumbers) {
            var n = this.pageData.paging;
            $$('.'+this.elemNumbers).each(function(e){
                e.update(n);
            });
        }
    },

    /* private method */
    counter: function () {
        this.pageData.current = this.pageData.limit;
        this.pageData.end     = this.pageData.page * this.pageData.limit;
        this.pageData.start   = (this.pageData.end - this.pageData.limit) + 1;

        if (this.pageData.end > this.pageData.total) {
            this.pageData.end     = this.pageData.total;
            this.pageData.current = this.pageData.end - this.pageData.start + 1;
        }

        this.pageData.counter = new Template(this.pageData.counterTpl).evaluate(this.pageData);

        if (this.elemCounter) {
            var c = this.pageData.counter;
            $$('.'+this.elemCounter).each(function(e){
                e.update(c);
            });
        }
    },

    /* private method */
    numbers: function () {
        var p   = this.pageData;
        var cls = null;
        var out = null;

        cls = (p.page == 1) ? 'disabled' : 'link';
        evn = (p.page == 1) ? '' : ' onclick="'+this.gotoMethod+'('+(p.page-1)+')"';
        out = '<div class="'+cls+'"'+evn+'>'+p.prev+'</div>';

        if (p.range && p.pages > p.range) {
            var half = parseInt(p.range / 2);
            var end  = p.page + half;

            if (end > p.pages) {
                end = p.pages;
            }

            var start = p.page - (p.range - (end - p.page));
            if (start <= 1) {
                start = 1;
                end   = p.page + (p.range - p.page) + 1;
            }

            for (var i=start; i<p.page; i++) {
                out += '<span class="link" onclick="'+this.gotoMethod+'('+i+')">'+i+'</span>';
            }

            out += '<span class="current">'+p.page+'</span>';

            start = p.page + 1;
            for (var i=start; i<end; i++) {
                out += '<span class="link" onclick="'+this.gotoMethod+'('+i+')">'+i+'</span>';
            }
        } else {
            for (var i=1; i<=p.pages; i++) {
                if (i == p.page) {
                    out += '<span class="current">'+i+'</span>';
                } else {
                    out += '<span class="link" onclick="'+this.gotoMethod+'('+i+')">'+i+'</span>';
                }
            }
        }

        cls  = (p.page == p.pages) ? 'disabled' : 'link';
        evn  = (p.page == p.pages) ? '' : ' onclick="'+this.gotoMethod+'('+(p.page+1)+')"';
        out += '<div class="'+cls+'"'+evn+'>'+p.next+'</div>';

        this.pageData.paging = out;

        if (this.elemNumbers) {
            var n = this.pageData.paging;
            $$('.'+this.elemNumbers).each(function(e){
                e.update(n);
            });
        }
    },

    gotoPage: function (page) {
        var p = this.pageData;

        if (p.page == page) {
            return;
        }

        this.pageData.page = page;
        this.counter();
        this.numbers();
    }
};

var ads = Class.create({
  options: $H({
      page: 1,
      keywords: null,
      catId: 0,
      minPrice: null,
      maxPrice: null,
      condition: 'all',
      type: 'all',
      location: null,
      newSearch: true
  }),

  initialize: function (url, className, tablename, pgOptions, options) {
      this.url       = url;
      this.name      = className;
      this.tablename = tablename;

      //Object.extend(this, paginator);
      this.paginator = paginator;

      if (typeof(pgOptions.elemCounter) != 'undefined') {
          this.paginator.elemCounter = pgOptions.elemCounter;
      }
      if (typeof(pgOptions.elemNumbers) != 'undefined') {
          this.paginator.elemNumbers = pgOptions.elemNumbers;
      }

      if (typeof(options) != 'undefined') {
          this.options.update(options);
      }
  },

  removeInvalid: function () {
      $$('div.error-message').each(function(e){
          e.remove();
          $('minPrice').removeClassName('err');
          $('maxPrice').removeClassName('err');
      });
  },
  priceSearch: function () {
      this.removeInvalid();
      if (!$F('minPrice') && !$F('maxPrice')) {
          $('maxPrice').next('input').insert({
              after:'<div class="error-message" style="display:inline; margin-left:5px;">please enter price range</div>'
          });
          $('minPrice').addClassName('err').focus();
          $('maxPrice').addClassName('err');

          $('minPrice').observe('change', this.removeInvalid);
          $('maxPrice').observe('change', this.removeInvalid);
          return false;
      }

      var options = { minPrice:null, maxPrice:null, page:1 };
      if ($F('minPrice')) {
          options.minPrice = $F('minPrice');
      }
      if ($F('maxPrice')) {
          options.maxPrice = $F('maxPrice');
      }

      this.getResults(options);
  },

  categorySearch: function (id) {
      var options = { catId:null, page:1 };

      if (id == 'all') {
          //TODO// AJAX get all main categories..
      } else {
          options.catId = id;
      }

      this.getResults(options);
  },

  getResults: function (options) {
      if (typeof(options) == 'object') { // new search has made and refined, update entire options
          $(this.tablename).down('thead').className = 'hide';
          $(this.tablename).down('tfoot').className = 'hide';
          this.options.update(options);
          var data = this.options.merge({ newSearch:1 });
      } else if (typeof(options) == 'number') { // same searching details, chaging page only
          this.options.set('page', options);
          this.paginator.gotoPage(options);
          var data = this.options.merge({ newSearch:0 });
      } else {
          var data = this.options;
      }

      var className     = this.name;
      var paginatorInit = function (json) {
          this.paginator.init('', '', className+'.getResults', json.total, json.limit, json.counterTpl);
      };

      var tableName = this.tablename;
      var otemplate = new Template(template);
      new Ajax.Request(this.url, {
          method: 'post',
          parameters: data.toObject(),
          onLoading: function() {
              if (typeof($(tableName).down('tbody.result')) == 'object') {
                  $(tableName).down('tbody.result').id = 'currentList';
                  new Effect.Fade('currentList', { from:1, to:0.2 });
              }
              if (!$(tableName).down('thead').className) {
                  //$(tableName).scrollTo();
                  new Effect.ScrollTo(tableName, { duration:0.5 });
              }
              $(tableName).down('tbody.loading').className = 'loading';
          },
          onComplete: function() {
              $(tableName).down('tbody.loading').addClassName('hide');
          },
          onFailure: function() {
              messageBox('Error', 0, 'Invalid search URL..');
          },
          onSuccess: function(transport, json) {
              if (json && json.status == -1) {
                  var errMsg = (json.message) ? json.message : 'Search return error..';
                  messageBox('Error', 0, errMsg);
              } else if (json && json.status == 0) {
                  $(tableName).down('thead').className = 'hide';
                  $(tableName).down('tfoot').className = 'hide';
                  $(tableName).down('tbody.noresult').removeClassName('hide');
              } else if (json && json.status == 1) {
                  var json = transport.responseText.evalJSON();

                  if ($('currentList')) {
                      $('currentList').remove();
                  }
                  if (json.total) {
                      $(tableName).down('thead').removeClassName('hide');
                      $(tableName).down('tfoot').removeClassName('hide');
                      $(tableName).down('tbody.noresult').className = 'noresult hide';
                      paginatorInit(json);
                  }
                  if (json.data) {
                      var date = altrow = '';
                      var out  = '<tbody class="result">';
                      json.data.each(function(d){
                          d.adsPath = json.adsPath;
                          d.imgPath = json.imgPath;
                          d.hasImg  = d.image ? 'block' : 'none';
                          d.altrow  = (altrow) ? '' : 'altrow';

                          if (d.created != date) {
                              date = d.created;
                          } else {
                              d.newDate = 'none';
                          }

                          altrow = (d.altrow) ? 1 : 0;
                          out += otemplate.evaluate(d);
                      });
                      $(tableName).insert(out+'</tbody>');
                  }
              }
          }
      });
  },

  test: function (opt) {
      alert(this.options.get(opt));
  }
});

var browse;
document.observe('dom:loaded', function() {
   browse = new ads('<?php e($this->base); ?>/adPosts/axSearch', 'browse', 'listingTable', '', {<?php
 echo isset($group)?" group:'".$group."',":'';
 echo isset($keywords)?" keywords:'".$keywords."',":'';
 echo isset($catId)?" catId:'".$catId."',":''; ?> page:1 });
   browse.getResults();
   //browse.test('catId');
});
</script>
<div class="adPosts">
<a href="<?php echo $this->base; ?>/"><?php __($sitename); ?></a> &gt;
<?php
   __($adPost['AdCategory']['parent']);

   if (isset($adPost['AdCategory']['category'])) {
       e(' &gt; <b>');
       __($adPost['AdCategory']['category']);
       e('</b>');
   }
?>
<p>&nbsp;</p>
<table style="margin:0;">
  <tr>
    <td width="235" style="padding-right:10px">
      <div class="refinesearch_header"><b><?php __('Refine Results'); ?></b></div>
      <div class="refinesearch">
        <div style="margin:5px; padding:3px; border-bottom:1px solid #B2B2B2;">
          <h3><?php __('Price'); ?>:</h3>
          <div><?php __('Specify price range'); ?> ($)</div>
          <input type="text" id="minPrice" maxlength="12" style="width:90px;" /> -
          <input type="text" id="maxPrice" maxlength="12" style="width:90px;" />
          <input type="button" value="<?php __('Go'); ?>" onclick="browse.priceSearch();" />
        </div>
        <div style="margin:5px; padding:3px">
          <h3><?php __('Category'); ?>:</h3>
          <span onclick="browse.categorySearch('all');" class="link"><?php __('All Categories'); ?></span>
        </div>
      </div>
    </td>
    <td>
      <table align="left" cellpadding="0" cellspacing="0" id="listingTable" style="margin-bottom:0; width:100%;">
        <thead class="hide">
          <tr>
            <th class="noborder normal"><span class="pageCounter"></span></th>
            <th class="noborder center"><?php __('Price'); ?></th>
            <th class="noborder center"><?php __('Location'); ?></th>
            <th class="noborder center"><?php __('Posted'); ?></th>
          </tr>
        </thead>
        <tfoot class="hide">
          <tr>
            <td colspan="4" align="right" style="border-bottom:0; padding-top:3px;">
              <div class="dr paging"><span class="pageNumbers"></span></div>
			  <div class="dr" style="margin:1px 8px 0 0;"><?php __('Page:');?></div>
            </td>
          </tr>
        </tfoot>
        <tbody class="loading hide">
          <tr>
            <td colspan="4" class="center" style="padding-top:10px;"><div class="loading"><?php __('loading..'); ?></div></td>
          </tr>
        </tbody>
        <tbody class="noresult hide">
          <tr>
            <td colspan="4" class="center" style="padding-top:10px;"><?php __('no result found'); ?></td>
          </tr>
        </tbody>
        <tbody class="template hide">
          <tr>
            <td colspan="4" style="display:#{newDate};" class="date"><span>#{created}</span></td>
          </tr>
          <tr class="#{altrow}">
            <td style="border-top:1px solid #ddd; padding-top:10px;">
              <b>#{type} <a href="#{adsPath}#{id}">#{title}</a></b>
            </td>
            <td class="center" style="border-top:1px solid #ddd; padding:10px 10px 0 10px;">#{price}&nbsp;</td>
            <td class="center" style="border-top:1px solid #ddd; padding:10px 10px 0 10px;">#{location}&nbsp;</td>
            <td class="center" style="border-top:1px solid #ddd; padding:10px 10px 0 10px;">#{time}</td>
	      </tr>
          <tr class="#{altrow}">
            <td>
              <table style="margin-bottom:10px;">
                <tr>
                  <td valign="top" style="padding:0;">
                    <a href="#{adsPath}#{id}" style="display:#{hasImg};background:none;"><img src="#{imgPath}#{image}" class="thumb" /></a>
                  </td>
                  <td valign="top" style="padding:0 10px 0 5px; vertical-align:top;">
                    <span style="font-size:11px;">#{description}</span>
                  </td>
                </tr>
              </table>
            </td>
            <td colspan="3">&nbsp;</td>
          </tr>
        </tbody>
      </table>
    </td>
  </tr>
</table>
</div>
